package com.gpframework.schedule;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gpframework.common.core.domain.entity.SysUser;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.utils.DateUtils;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.common.weixin.common.constants.WeiXinConstants;
import com.gpframework.common.weixin.common.message.base.AccessToken;
import com.gpframework.common.weixin.common.message.base.Template;
import com.gpframework.module.manufacture.domain.GpProductionScheduling;
import com.gpframework.module.manufacture.service.IGpProductionSchedulingService;
import com.gpframework.module.system.mapper.SysUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * gpframework
 * ==================================================================
 * CopyRight © 2017-2099 广州宏略信息科技有限公司
 * 官网地址：http://www.greatplan.com.cn
 * <p>
 * ------------------------------------------------------------------
 * 这不是一个自由软件！未经本公司授权您只能在不用于商业目的的前提下
 * 对本程序代码进行修改和使用；不允许对本程序代码以任何目的的再发布。
 * ==================================================================
 *
 * @ClassName ScheduleTask
 * @Author gpframework
 * @Date 2020-12-30
 * @Version 1.0.0
 * EnableScheduling : 1.开启定时任务
 * EnableAsync :2.开启多线程
 */
@Component
@EnableScheduling
@EnableAsync
@Slf4j
public class ScheduleTask {

    public static final Logger logger = LoggerFactory.getLogger(ScheduleTask.class);
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private IGpProductionSchedulingService iGpProductionSchedulingService;


    /**
     * 定时消息提醒
     * 每天21：00执行一次
     */
    @Scheduled(cron = "0 0 21 * * ?")
    public void timedMessageReminder() {
        log.info("------消息推送任务开始-------");
        // 发送小程序消息
        appletSend();
        // 发送公众号消息
        officialAccountSend();
        log.info("------消息推送任务结束-------");
    }

    private void appletSend() {
        AccessToken accessToken = new AccessToken();
        String requestUrl = WeiXinConstants.ACCESS_TOKEN_URL.replace("APPID", WeiXinConstants.APP_ID).replace("APPSECRET", WeiXinConstants.APP_SECRET);
        String requestStr = HttpUtil.get(requestUrl);
        if (!org.springframework.util.StringUtils.isEmpty(requestStr)) {
            accessToken = JSONUtil.toBean(requestStr, AccessToken.class);
            if (accessToken.getErrcode() != null) {
                log.error("获取微信Token失败：" + accessToken.getErrcode());
                return;
            }
        }
        if (StringUtils.isNull(accessToken) || StringUtils.isBlank(accessToken.getAccess_token())) {
            log.error("accessToken为空");
            return;
        }
        // 林总
        SysUser sysUser1 = sysUserMapper.selectUserByUserName("13922280093");
        if (sysUser1 != null && StringUtils.isNotBlank(sysUser1.getOpenid())) {
            sendMsg(accessToken, sysUser1.getOpenid());
        }
        // 李总
        SysUser sysUser2 = sysUserMapper.selectUserByUserName("19802000939");
        if (sysUser2 != null && StringUtils.isNotBlank(sysUser2.getOpenid())) {
            sendMsg(accessToken, sysUser2.getOpenid());
        }
        // 符经理
        SysUser sysUser3 = sysUserMapper.selectUserByUserName("13392457466");
        if (sysUser3 != null && StringUtils.isNotBlank(sysUser3.getOpenid())) {
            sendMsg(accessToken, sysUser3.getOpenid());
        }
        // 测试账号
        SysUser sysUser4 = sysUserMapper.selectUserByUserName("18300000003");
        if (sysUser4 != null && StringUtils.isNotBlank(sysUser4.getOpenid())) {
            sendMsg(accessToken, sysUser4.getOpenid());
        }
    }


    private void officialAccountSend() {
        AccessToken accessToken = new AccessToken();
        String requestUrl = WeiXinConstants.ACCESS_TOKEN_URL.replace("APPID", WeiXinConstants.WX_APP_ID).replace("APPSECRET", WeiXinConstants.WX_APP_SECRET);
        String requestStr = HttpUtil.get(requestUrl);
        if (!org.springframework.util.StringUtils.isEmpty(requestStr)) {
            accessToken = JSONUtil.toBean(requestStr, AccessToken.class);
            if (accessToken.getErrcode() != null) {
                log.error("获取微信Token失败：" + accessToken.getErrcode());
                return;
            }
        }
        if (StringUtils.isNull(accessToken) || StringUtils.isBlank(accessToken.getAccess_token())) {
            log.error("accessToken为空");
            return;
        }
        List<SysUser> sysUserList = sysUserMapper.selectMessageList();
        for (SysUser sysUser : sysUserList) {
            // 林总
            sendOfficialAccountMsg(accessToken, sysUser.getOpenid());
        }
//        // 林总
//        sendOfficialAccountMsg(accessToken, "oPjU56hN9vpvVLC1Xv5cy9NoX5RQ");
//        // 李总
//        sendOfficialAccountMsg(accessToken, "oPjU56pJMPXmq6m8c3_4d_ayDd6o");
//        // 符经理
//        sendOfficialAccountMsg(accessToken, "oPjU56jp4Vogk1Buoi-yZh8AARM8");
//        // 测试账号
//        sendOfficialAccountMsg(accessToken, "oPjU56p9yV5QvbC0AuY9IVJ1fe7I");
//        // 星霜荏苒
//        sendOfficialAccountMsg(accessToken, "oPjU56p7B7HMNdnp7SyFlZ4VGN0c");
    }

    /**
     * 发送公众号通知
     * @param accessToken
     * @return
     */
    private void sendOfficialAccountMsg(AccessToken accessToken, String openId) {
        Template template = Template.New()
                .setMiniprogram_state("formal") // developer为开发版: trial为体验版:formal为正式版，默认为正式版
                .setLang("zh_CN")
                // openid
                .setTouser(openId)
                .setPage("/pack-user/report/index");
        template.setTemplate_id("nrULpU5PhOLa7PH6gz6oQf9z3I3Y-LkElIeAPUkouYg");
        template.add("thing9", "您的每日报表已生成，可点击查看详情");
        template.add("time6", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date()));
        template.addMiniprogram("appid", WeiXinConstants.APP_ID);
        template.addMiniprogram("pagepath", "/pack-user/report/index?time="+DateUtils.parseDateToStr("yyyy-MM-dd", new Date()));
        String body = HttpRequest.post(WeiXinConstants.APP_ADVANCED_SUBSCRIBE_SEND_URL + accessToken.getAccess_token())
                .body(template.build())
                .execute().body();
        log.debug("定时消息提醒返回" + body);
    }

    /**
     * 发送小程序通知
     * @param accessToken
     * @return
     */
    private void sendMsg(AccessToken accessToken, String openId) {
        Template template = Template.New()
                .setMiniprogram_state("formal") // developer为开发版: trial为体验版:formal为正式版，默认为正式版
                .setLang("zh_CN")
                // openid
                .setTouser(openId)
                .setPage("/pack-user/report/index");
        template.setTemplate_id("6V0OTe-5FcC-T97qsEMDPJ8y5KebWUO7xCI3tqTNUrk");
        template.add("thing3", "您的每日报表已生成，可点击查看详情");
        template.add("date1", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date()));
        String body = HttpRequest.post(WeiXinConstants.ADVANCED_SUBSCRIBE_SEND_URL + accessToken.getAccess_token())
                .body(template.build())
                .execute().body();
        log.debug("定时消息提醒返回" + body);
    }

    /**
     * 定时更新环思智慧进度
     * 每10分钟执行一次
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void updateProgress() {
        // 查询所有未生成生产送货单的生产排单
        List<GpProductionScheduling> list = iGpProductionSchedulingService.list(new LambdaQueryWrapper<GpProductionScheduling>().eq(GpProductionScheduling::getDeliveryNoteFlag, YesNoEnum.NO.getKey()).eq(GpProductionScheduling::getDelStatus, YesNoEnum.NO.getKey()));
        for (GpProductionScheduling gpProductionScheduling : list) {
            if (gpProductionScheduling.getPlaceOrdersTime() != null && StringUtils.isNotBlank(gpProductionScheduling.getDyeVatNo())) {
                this.updateProgressStatus(gpProductionScheduling);
            }
        }
    }

    private void updateProgressStatus(GpProductionScheduling gpProductionScheduling) {
        String body = HttpRequest.post("http://hsapp.huansi.org/BIShow.aspx?ParaStr=q%2bO90Q%2bRp9NhmRsgJcLfPA%3d%3d&Language=cn")
                .form("__VIEWSTATE", "/wEPDwUKMTg0NDY4MzI5M2RkRr4cFiGNvEYceIzs7eIUBox7hL6erQowSqb1q72ksPE=")
                .form("__VIEWSTATEGENERATOR", "4D860858")
                .form("dOrderDateBeg", DateUtils.dateTime(gpProductionScheduling.getPlaceOrdersTime()))
                .form("dOrderDateEnd", DateUtils.dateTime(gpProductionScheduling.getPlaceOrdersTime()))
                .form("sMaterialLot", gpProductionScheduling.getDyeVatNo())
                .execute().body();
        String substring = body.substring(body.lastIndexOf("<tr align='center'>"), body.lastIndexOf("</tr>"));
        System.out.println("substring = " + substring);
        // 使用正则表达式提取每个<td>标签中的内容
        List<String> list = new ArrayList<>();
        Pattern pattern = Pattern.compile("<font[^>]*>(.*?)</font>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(substring);
        while (matcher.find()) {
            String value = matcher.group(1).trim();
            if (!value.isEmpty()) {
                list.add(value);
            }
        }
        if (!CollectionUtils.isEmpty(list) && list.size() > 5) {
            String progressStatus = list.get(4);
            gpProductionScheduling.setProgressStatus(progressStatus);
            iGpProductionSchedulingService.updateById(gpProductionScheduling);
        }
    }

    public static void main(String[] args) {
        String body = HttpRequest.post("http://hsapp.huansi.org/BIShow.aspx?ParaStr=q%2bO90Q%2bRp9NhmRsgJcLfPA%3d%3d&Language=cn")
                .form("__VIEWSTATE", "/wEPDwUKMTg0NDY4MzI5M2RkRr4cFiGNvEYceIzs7eIUBox7hL6erQowSqb1q72ksPE=")
                .form("__VIEWSTATEGENERATOR", "4D860858")
                .form("dOrderDateBeg", "2023-09-21")
                .form("dOrderDateEnd", "2023-09-21")
                .form("sMaterialLot", "230921027")
                .execute().body();
        log.debug("定时消息提醒返回" + body);
        String substring = body.substring(body.lastIndexOf("<tr align='center'>"), body.lastIndexOf("</tr>"));
        System.out.println("substring = " + substring);
        // 使用正则表达式提取每个<td>标签中的内容
        List<String> list = new ArrayList<>();
        Pattern pattern = Pattern.compile("<font[^>]*>(.*?)</font>", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(substring);
        while (matcher.find()) {
            String value = matcher.group(1).trim();
            if (!value.isEmpty()) {
                list.add(value);
            }
        }
        if (!CollectionUtils.isEmpty(list) && list.size() > 5) {
            String progressStatus = list.get(4);
            System.out.println("progressStatus = " + progressStatus);
        }
    }

}
